package com.jcfk.system.service;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.core.constant.Constants;
import com.jcfk.common.core.context.SpringContextUtils;
import com.jcfk.common.websocket.model.SocketMessage;
import com.jcfk.system.domain.dto.SysOrganizationDTO;
import com.jcfk.system.domain.model.SendMsgModel;
import com.jcfk.system.domain.po.*;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 发送站内消息
 */
@Component("onSiteMessageService")
public class OnSiteMessageService {

    private static SysMessageSendUserService sysMessageSendUserService;


    private static SysMessageSendRecordService sysMessageSendRecordService;


    private static SysMessageSendRecordDetailsService sysMessageSendRecordDetailsService;

    private static SysBusinessGroupUserService sysBusinessGroupUserService;
    /**
     * 多级分类服务
     */
    private static RefUserOrganizationMappingService refUserOrganizationMappingService;

    private static SysInternalMessageService sysInternalMessageService;

    private static WebSocketMessageService webSocketMessageService;
    private static SysOrganizationService sysOrganizationService;

    // 使用静态代码块及SpringContextUtils获取对象
    static {
        sysMessageSendUserService = SpringContextUtils.getBean(SysMessageSendUserService.class);
        sysMessageSendRecordService = SpringContextUtils.getBean(SysMessageSendRecordService.class);
        sysMessageSendRecordDetailsService = SpringContextUtils.getBean(SysMessageSendRecordDetailsService.class);
        sysBusinessGroupUserService = SpringContextUtils.getBean(SysBusinessGroupUserService.class);
        refUserOrganizationMappingService = SpringContextUtils.getBean(RefUserOrganizationMappingService.class);
        sysInternalMessageService = SpringContextUtils.getBean(SysInternalMessageService.class);
        webSocketMessageService = SpringContextUtils.getBean(WebSocketMessageService.class);
        sysOrganizationService = SpringContextUtils.getBean(SysOrganizationService.class);
    }

    /**
     * 发送内部消息
     */
    public void onSiteMessage(SendMsgModel message, SysMessageSendRecord record) {
        // 接收人
        String[] fruits = {"3", "4"};
        QueryWrapper<SysMessageSendUser> sysMessageSendUserQueryWrapper = new QueryWrapper<>();
        sysMessageSendUserQueryWrapper.lambda().eq(SysMessageSendUser::getTempleId, record.getTempleId()).eq(SysMessageSendUser::getDeleted, 0).notIn(SysMessageSendUser::getType, fruits);
        List<SysMessageSendUser> list = sysMessageSendUserService.list(sysMessageSendUserQueryWrapper);

        // 用户id
        List<String> userIds = new ArrayList<>();
        List<String> groupId = new ArrayList<>();

        for (SysMessageSendUser user : list) {
            if (!StringUtils.isEmpty(user.getOrganizationId()) && StringUtils.isEmpty(message.getOrganizationId())) {
                message.setOrganizationId(user.getOrganizationId());
            }
            if (!StringUtils.isEmpty(user.getRecevieUserId())) userIds.add(user.getRecevieUserId());
            if (!StringUtils.isEmpty(user.getGroupId())) groupId.add(user.getGroupId());
        }


        // 根据组织 赋值接收人id
        if (!StringUtils.isEmpty(message.getOrganizationId())) {
            SysOrganizationDTO sysOrganization = sysOrganizationService.get(message.getOrganizationId());
            QueryWrapper<SysOrganization> sysOrganizationQueryWrapper = new QueryWrapper<>();
            sysOrganizationQueryWrapper.lambda().likeRight(SysOrganization::getAllId, sysOrganization.getAllId())
                    .eq(SysOrganization::getDeleted,0);
            List<SysOrganization> organizations = sysOrganizationService.list(sysOrganizationQueryWrapper);
            List<String> oragIds = organizations.stream().map(SysOrganization::getId).collect(Collectors.toList());

            QueryWrapper<RefUserOrganizationMapping> refUserOrganizationMappingQueryWrapper = new QueryWrapper<>();
            refUserOrganizationMappingQueryWrapper.lambda().in(RefUserOrganizationMapping::getOrganizationId, oragIds);
            List<String> ids = refUserOrganizationMappingService.list(refUserOrganizationMappingQueryWrapper).stream().map(RefUserOrganizationMapping::getUserId).collect(Collectors.toList());
            message.getReceiveUserIds().addAll(ids);
        }

        // 根据组别 赋值接收人id
        if (message.getBusinessGroupId() == null || message.getBusinessGroupId().size() > 0) {
            message.setBusinessGroupId(groupId);
            if (message.getBusinessGroupId() == null || message.getBusinessGroupId().size() > 0) {
                QueryWrapper<SysBusinessGroupUser> sysBusinessGroupUserQueryWrapper = new QueryWrapper<>();
                sysBusinessGroupUserQueryWrapper.lambda().in(SysBusinessGroupUser::getBusinessId, message.getBusinessGroupId()).eq(SysBusinessGroupUser::getDeleted, 0);
                List<String> ids = sysBusinessGroupUserService.list(sysBusinessGroupUserQueryWrapper).stream().map(SysBusinessGroupUser::getUserId).collect(Collectors.toList());
                message.getReceiveUserIds().addAll(ids);
            }
        }

        // 接收人id赋值
        if (message.getReceiveUserIds() == null && message.getReceiveUserIds().size() <= 0) {
            message.getReceiveUserIds().addAll(userIds);
        }

        // 接收人去重
        message.setReceiveUserIds(message.getReceiveUserIds().stream().distinct().collect(Collectors.toList()));

        List<SysInternalMessage> sendMessage = SendMessage(message, record);
        for (SysInternalMessage internalMessage : sendMessage) {
            SocketMessage socketMessage = new SocketMessage();
            socketMessage.setMessageType("internalMessage");
            socketMessage.setUrl(message.getUrl());
            socketMessage.setMsgId(internalMessage.getId());
            socketMessage.setMessageContent(message.getTitle());
            socketMessage.setMessageLevel(message.getMessageLevel());
            webSocketMessageService.sendMessage(internalMessage.getRecevieUserId(), socketMessage);
        }


        List<SysMessageSendRecordDetails> records = new ArrayList<>();
        // 发送记录入库
        for (String receiveUserId : message.getReceiveUserIds()) {
            SysMessageSendRecordDetails details = new SysMessageSendRecordDetails();
            details.setRecevieUserId(receiveUserId);
            details.setTitle(record.getTitle());
            details.setContent(message.getMsgBody());
            details.setMessageId(record.getId());
            details.setCreatedUserId(record.getCreatedUserId());
            details.setCreateTime(new Date());
            details.setCreatedUserId(record.getCreatedUserId());
            details.setCreatedUserName(record.getCreatedUserName());
            records.add(details);
        }

        if (records.size() > 0) sysMessageSendRecordDetailsService.saveBigBatch(records);

        // 更新状态
        record.setMessageStatus(1);
        sysMessageSendRecordService.updateById(record);
    }

    // 发送消息
    public List<SysInternalMessage> SendMessage(SendMsgModel msgInfo, SysMessageSendRecord record) {

        List<SysInternalMessage> list = new ArrayList<>();

        // 组装消息
        for (String userId : msgInfo.getReceiveUserIds()) {
            SysInternalMessage message = new SysInternalMessage();
            message.setTitle(msgInfo.getTitle());
            message.setUrl(msgInfo.getUrl());
            message.setMsgBody(msgInfo.getMsgBody());
            message.setSendTime(new Date());
            message.setRecevieUserId(userId);
            message.setReaded(Constants.NO);
            message.setEnabled(Constants.YES);
            message.setSendTime(new Date());
            message.setSendUserId(record.getCreatedUserId());
            message.setCreatedUserId(record.getCreatedUserId());
            message.setCreatedUserName(record.getCreatedUserName());
            message.setCreateTime(new Date());

            list.add(message);
        }

        // 入库
        if (list.size() > 0) sysInternalMessageService.saveBigBatch(list);

        return list;
    }

}
